<template>
  <el-card class="booking-manage-container">
    <div class="header">
      <h2>预约审核</h2>
      <div class="filters">
        <el-select v-model="filterStatus" placeholder="状态筛选" clearable>
          <el-option label="待审核" value="0" />
          <el-option label="已通过" value="1" />
          <el-option label="已拒绝" value="2" />
          <el-option label="已取消" value="3" />
        </el-select>
        <el-input v-model="searchUser" placeholder="搜索申请人" clearable style="width: 200px" />
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        />
        <el-button type="primary" :icon="Search" @click="loadBookings">搜索</el-button>
      </div>
    </div>

    <el-table
        :data="filteredBookings"
        style="width: 100%"
        stripe
        v-loading="loading"
    >
      <el-table-column prop="userName" label="申请人" width="120" />
      <el-table-column prop="userId" label="学工号" width="120" />
      <el-table-column prop="room" label="会议室" width="150" />
      <el-table-column prop="date" label="日期" width="120" sortable />
      <el-table-column prop="time" label="时间段" width="180">
        <template #default="{ row }">
          {{ row.startTime }} - {{ row.endTime }}
        </template>
      </el-table-column>
      <el-table-column prop="purpose" label="用途" />
      <el-table-column prop="status" label="状态" width="100" sortable>
        <template #default="{ row }">
          <el-tag :type="statusType[row.status]" size="small">
            {{ statusText[row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <el-button
              v-if="row.status === 0"
              size="small"
              type="success"
              @click="handleApprove(row)"
          >
            通过
          </el-button>
          <el-button
              v-if="row.status === 0"
              size="small"
              type="danger"
              @click="handleReject(row)"
          >
            拒绝
          </el-button>
          <el-button
              size="small"
              @click="handleView(row)"
              :icon="View"
          >
            详情
          </el-button>
          <el-button
              v-if="row.status === 1"
              size="small"
              type="warning"
              @click="handleCancel(row)"
          >
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
          background
          layout="prev, pager, next, sizes, total"
          :total="totalItems"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>

    <!-- 预约详情对话框 -->
    <el-dialog v-model="detailVisible" title="预约详情" width="600px">
      <el-descriptions :column="2" border v-if="currentBooking">
        <el-descriptions-item label="申请人">{{ currentBooking.userName }}</el-descriptions-item>
        <el-descriptions-item label="学工号">{{ currentBooking.userId }}</el-descriptions-item>
        <el-descriptions-item label="会议室">{{ currentBooking.room }}</el-descriptions-item>
        <el-descriptions-item label="容纳人数">{{ currentBooking.capacity }}人</el-descriptions-item>
        <el-descriptions-item label="预约日期">{{ currentBooking.date }}</el-descriptions-item>
        <el-descriptions-item label="时间段">{{ currentBooking.startTime }} - {{ currentBooking.endTime }}</el-descriptions-item>
        <el-descriptions-item label="预约用途" :span="2">
          {{ currentBooking.purpose }}
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ currentBooking.applyTime }}</el-descriptions-item>
        <el-descriptions-item label="处理时间">{{ currentBooking.processTime || '--' }}</el-descriptions-item>
        <el-descriptions-item label="当前状态" :span="2">
          <el-tag :type="statusType[currentBooking.status]">
            {{ statusText[currentBooking.status] }}
          </el-tag>
          <span v-if="currentBooking.rejectReason" class="reject-reason">
            拒绝原因: {{ currentBooking.rejectReason }}
          </span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Search, View } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Booking } from './types'

// 模拟数据生成
const generateBookings = (count = 20): Booking[] => {
  // 生成30个统一命名的会议室
  const rooms = Array.from({length: 30}, (_, i) => {
    const buildingIndex = i % 7;
    const building = String.fromCharCode(65 + buildingIndex); // A-G
    const floor = Math.floor(i / 7) + 1;
    const roomNum = 100 + (i % 20);
    return `${building}区${building}${floor}号楼${roomNum}`;
  });

  const users = [
    { name: '张三', id: '20230001' },
    { name: '李四', id: '20230002' },
    { name: '王五', id: '20230003' },
    { name: '赵六', id: '20230004' },
    { name: '钱七', id: '20230005' }
  ]
  const purposes = [
    '项目会议', '学术讨论', '团队建设', '毕业答辩',
    '学生活动', '教师研讨', '社团活动', '面试考核'
  ]

  const bookings: Booking[] = []
  const now = new Date()

  for (let i = 0; i < count; i++) {
    const user = users[Math.floor(Math.random() * users.length)]
    const room = rooms[Math.floor(Math.random() * rooms.length)]
    const date = new Date(now.getTime() + Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000)

    const startHour = 8 + Math.floor(Math.random() * 10)
    const endHour = startHour + Math.floor(Math.random() * 3) + 1

    bookings.push({
      id: i + 1,
      userName: user.name,
      userId: user.id,
      room: room,
      capacity: 20 + Math.floor(Math.random() * 30),
      date: `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`,
      startTime: `${startHour.toString().padStart(2, '0')}:00`,
      endTime: `${endHour.toString().padStart(2, '0')}:00`,
      purpose: purposes[Math.floor(Math.random() * purposes.length)],
      applyTime: new Date(now.getTime() - Math.floor(Math.random() * 7) * 24 * 60 * 60 * 1000).toLocaleString(),
      status: Math.floor(Math.random() * 4), // 0-3
      rejectReason: Math.random() > 0.7 ? '会议室已被占用' : null,
      processTime: Math.random() > 0.3 ? new Date(now.getTime() - Math.floor(Math.random() * 3) * 24 * 60 * 60 * 1000).toLocaleString() : null
    })
  }

  return bookings
}

// 状态定义
const statusText = ['待审核', '已通过', '已拒绝', '已取消']
const statusType = ['warning', 'success', 'danger', 'info']

// 数据状态
const allBookings = ref<Booking[]>([])
const filteredBookings = ref<Booking[]>([])
const currentBooking = ref<Booking | null>(null)
const loading = ref(true)
const filterStatus = ref('')
const searchUser = ref('')
const dateRange = ref([])
const detailVisible = ref(false)

// 分页参数
const totalItems = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)

// 初始化加载数据
onMounted(() => {
  loadBookings()
})

// 加载预约数据
const loadBookings = () => {
  loading.value = true
  setTimeout(() => {
    allBookings.value = generateBookings(50)
    applyFilters()
    loading.value = false
  }, 800)
}

// 应用筛选条件
const applyFilters = () => {
  let result = [...allBookings.value]

  // 状态筛选
  if (filterStatus.value) {
    result = result.filter(b => b.status.toString() === filterStatus.value)
  }

  // 用户搜索
  if (searchUser.value) {
    const keyword = searchUser.value.toLowerCase()
    result = result.filter(b =>
        b.userName.toLowerCase().includes(keyword) ||
        b.userId.toLowerCase().includes(keyword)
    )
  }

  // 日期筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const [start, end] = dateRange.value
    result = result.filter(b => {
      const bookingDate = new Date(b.date)
      return bookingDate >= start && bookingDate <= end
    })
  }

  totalItems.value = result.length
  updatePageData(result)
}

// 更新分页数据
const updatePageData = (data: Booking[]) => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  filteredBookings.value = data.slice(start, end)
}

// 分页事件处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  applyFilters()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  applyFilters()
}

// 操作处理函数
const handleApprove = (booking: Booking) => {
  ElMessageBox.confirm('确定通过此预约申请吗?', '审核确认', {
    confirmButtonText: '通过',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    booking.status = 1
    booking.processTime = new Date().toLocaleString()
    ElMessage.success('已通过预约申请')
  })
}

const handleReject = (booking: Booking) => {
  ElMessageBox.prompt('请输入拒绝原因', '拒绝申请', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPattern: /\S+/,
    inputErrorMessage: '请输入拒绝原因'
  }).then(({ value }) => {
    booking.status = 2
    booking.rejectReason = value
    booking.processTime = new Date().toLocaleString()
    ElMessage.success(`已拒绝申请，原因：${value}`)
  })
}

const handleView = (booking: Booking) => {
  currentBooking.value = booking
  detailVisible.value = true
}

const handleCancel = (booking: Booking) => {
  ElMessageBox.confirm('确定取消此预约吗?', '取消预约', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    booking.status = 3
    booking.processTime = new Date().toLocaleString()
    ElMessage.success('预约已取消')
  })
}
</script>

<style scoped lang="scss">
.booking-manage-container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 15px;

    h2 {
      margin: 0;
      font-size: 24px;
      color: #333;
    }
  }

  .filters {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .reject-reason {
    display: block;
    margin-top: 8px;
    color: #f56c6c;
    font-size: 14px;
  }
}

.el-descriptions {
  margin-top: 10px;

  :deep(.el-descriptions__label) {
    width: 100px;
    font-weight: bold;
  }
}
</style>